<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="6">
        <div>
          <category-list @select="categorySelect"></category-list>
        </div>
      </el-col>
      <el-col :span="18">
        <div>
          <el-button @click="getAllCategory(); addDialog = true">新增分组</el-button>
        </div>
        <div>
          <el-table :data="attrgroup">
            <el-table-column prop="id" label="编号" width="100"/>
            <el-table-column prop="iconId" label="图标" width="120"/>
            <el-table-column prop="groupName" label="分组名" width="180"/>
            <el-table-column prop="descript" label="描述" width="180"/>
            <!--          TODO 需要改成分类名-->
            <el-table-column prop="categoryId" label="所属三级分类"/>
            <el-table-column label="操作">
              <template #default="scope">
                <el-text type="primary" @click="assoAttrAttrgroup(scope.row)">关联</el-text>
                <el-divider direction="vertical"/>
                <el-text type="danger" @click="openUpdate(scope.row)">修改</el-text>
                <el-divider direction="vertical"/>
                <el-text type="danger" @click="openDel(scope.row)">删除</el-text>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <!--新增对话框-->
    <el-dialog v-model="addDialog" title="新增分组" width="30%" @close="fromRef.resetFields()">
      <el-form :model="addAttrGroup" size="large" label-width="80px" label-position="left" ref="fromRef" :rules="rules">
        <el-form-item label="图标" prop="iconId">
          <el-upload
              class="upload-demo"
              name="files"
              :action="$upFile"
              :limit="1"
              :data="fileInfoVo"
              :headers="header"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500KB.
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="addAttrGroup.groupName" placeholder="请输入分组的名称"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="addAttrGroup.sort"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="descript">
          <el-input v-model="addAttrGroup.descript" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader v-model="addAttrGroup.categoryId" :options="categorys" clearable :show-all-levels="false"
                       :props="showProps"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialog = false">取消</el-button>
        <el-button type="primary" @click="addSumbit(fromRef)">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="updateDialog" title="修改分组" width="30%" @close="fromRef.resetFields()">
      <el-form :model="addAttrGroup" size="large" label-width="80px" label-position="left" ref="fromRef" :rules="rules">
        <el-form-item label="图标" prop="iconId">
          <el-upload
              class="upload-demo"
              name="files"
              :action="$upFile"
              :limit="1"
              :data="fileInfoVo"
              :headers="header"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500KB.
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="selectGroup.groupName" placeholder="请输入分组的名称"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="selectGroup.sort"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="descript">
          <el-input v-model="selectGroup.descript" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader v-model="selectGroup.categoryId" :options="categorys" clearable :show-all-levels="false"
                       :props="showProps" @visible-change="getAllCategory"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialog = false">取消</el-button>
        <el-button type="primary" @click="updateSumbit(fromRef)">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="assoAttrAttrgroupDialog"
        title="分组属性关联列表"
        width="40%"
        :before-close="handleClose"
        draggable
    >
      <div>
        <div>
          <el-row :gutter="20">
            <el-col :span="6">
              <div>
                <el-button @click="openAddAsso">新建关联</el-button>
              </div>
            </el-col>
            <el-col :span="6">
              <el-button>批量删除</el-button>
            </el-col>
          </el-row>
          <div>
            <el-table :data="attrList">
              <el-table-column prop="attrName" label="属性名" width="100"/>
              <el-table-column prop="attrType" label="属性类型" width="100"/>
              <el-table-column prop="searchType" label="是否可以搜索" width="150"/>
              <el-table-column prop="valueSelect" label="可选值列表" width="150"/>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="assoAttrAttrgroupDialog = false">取消</el-button>
        <el-button type="primary" @click="assoAttrAttrgroupDialog = false">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>
    <!--  新建关联弹窗-->
    <el-dialog
        v-model="addAssoDialog"
        title="新建关联"
        width="30%"
        :before-close="handleClose"
        draggable
    >
      <div>
        <el-row :gutter="20">
          <el-col :span="16">
            <div>
              <el-input placeholder="请输入内容"></el-input>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-button>查询</el-button>
            </div>
          </el-col>
        </el-row>
        <el-table :data="noAssoAttr" style="width: 100%" @selection-change="select">
          <el-table-column type="selection"/>
          <el-table-column prop="id" label="编号"/>
          <el-table-column prop="attrName" label="属性名"/>
        </el-table>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addAssoDialog = false">取消</el-button>
        <el-button type="primary" @click="assoSubmit">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import CategoryList from '@/components/CategoryList/CategoryList'
import {getAllCategoryToTree} from "@/api/home/goods/category";
import {
  add,
  getAttrGroupByCategoryId,
  getAttrByAttrGroupId,
  getNoAssoAttrByCategoryId,
  addAssoAttrAndGroup,
  modifyGroup,
  delGroupList
} from '@/api/home/goods/attrGroup'
import {getToken} from "@/util/token/tokenUtil";
import {ElMessage, ElMessageBox} from 'element-plus'

let fromRef = ref()//表单清空等需要的属性
let attrgroup = ref([])
let addDialog = ref(false)
let updateDialog = ref(false)
let categorys = ref([])
let selectInfo = reactive({
  category: '',
  attrGroup: '',
  attr: []
})

/*属性分组与属性关联数据*/
let assoAttrAttrgroupDialog = ref(false)
let attrList = ref([])
/*新建关联*/
let addAssoDialog = ref(false)
let noAssoAttr = ref([])

let fileInfoVo = ref({
  bucketName: 'goods',
  folderName: 'attrgroupicon',
  fileName: '',
  filePath: ''
})
const header = {
  token: getToken('token')
}

let addAttrGroup = reactive({
  groupName: '',
  sort: '',
  descript: '',
  iconId: '',
  categoryId: ''
})
let showProps = reactive({
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
let selectGroup = ref({})
let delGroupData = ref([])

/*获取三级分类数据*/
function getAllCategory() {
  getAllCategoryToTree().then(res => {
    categorys.value = res.data
  })
}

/*分组图标上传回调*/
function handleAvatarSuccess(res) {
  addAttrGroup.iconId = res.data
}

function getAttrGroupList(categoryId) {
  getAttrGroupByCategoryId(categoryId).then(res => {
    attrgroup.value = res.data
  })
}

function categorySelect(node) {
  //TODO 此处不知道是否需要，只需要注意新增表单的默认所属分类(左侧点击了三级分类，再点击新增的时候默认所属分类显示）这里是否会用到，否则就可以删除
  selectInfo.category = node
  getAttrGroupList(node.id)
}

function addSumbit(r) {
  r.validate(vaild => {
    if (vaild) {
      add(addAttrGroup)
      //TODO 应当刷新，然后展开添加的节点
      addDialog.value = false
    } else return false
  })
}

function assoAttrAttrgroup(node) {
  assoAttrAttrgroupDialog.value = true
  selectInfo.attrGroup = node
  getAttrByAttrGroupId(node.id).then(res => {
    attrList.value = res.data
  })
}

/*打开新建关联的窗口，获取当前分类下没有关联的属性*/
function openAddAsso() {
  getNoAssoAttrByCategoryId(selectInfo.category.id).then(res => {
    noAssoAttr.value = res.data
  })
  addAssoDialog.value = true
}

function select(val) {
  selectInfo.attr = val
}

function assoSubmit() {
  /*数据封装，后端需要的是一个数组*/
  let assoData = selectInfo.attr.map((item) => {
    return {
      attrId: item.id,
      attrGroupId: selectInfo.attrGroup.id
    }
  })
  addAssoAttrAndGroup(assoData)
  addAssoDialog.value = false
}

/*修改*/
function openUpdate(node) {
  selectGroup.value = node
  updateDialog.value = true
}

function updateSumbit(r) {
  modifyGroup(selectGroup.value).then(() => {
    getAttrGroupList(selectInfo.category.id)
    updateDialog.value = false
  })
  r.resetFields()
}

function openDel(node) {
  ElMessageBox.confirm(
      `你确定要删除${node.groupName}分组吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        delGroupList([node.id])
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消成功',
        })
      })
}

/*表单校验规则*/
let rules = reactive({
  // iconId: [
  //   {required: true, message: '请上传该分组图标', trigger: 'blur'}
  // ],
  groupName: [
    {required: true, message: '分组名称不能为空', trigger: 'blur'}
  ],
  descript: [
    {required: true, message: '描述不能为空', trigger: 'blur'}
  ],
  categoryId: [
    {required: true, message: '所属三级分类不能为空', trigger: 'blur'}
  ]
})
</script>

<style scoped>

</style>
